<template>
    <div class="form-container">
        <el-alert v-if="paramsModified && showModifiedWarning" type="error" :closable="false" :title="modifiedWarning">
        </el-alert>
        <div v-for="(item, index) in paramsModel" :key="item.name">

            <div v-if="item.type !== 'array'">
                <dynamic-form-item :label="item.label || item.name"
                    :model-value="paramValues[index].value" :component-model="item"
                    @update:model-value="onUpdateSingleItem(index, $event)">
                </dynamic-form-item>
            </div>
            <dynamic-items-list v-else :params-model="item" :param-values="paramValues[index]"
                @update-value="onUpdate(index, $event)" :type="item.component"></dynamic-items-list>
        </div>
    </div>

</template>

<script lang="ts" setup>
import { defineProps, defineExpose, ref } from "vue"
import { ParamsType, ParamValuesType, ParamValue, FormValueTypes } from "./models"
import DynamicItemsList from "./DynamicItemsList.vue";
import DynamicFormItem from "./DynamicFormItem.vue";
import { ElAlert } from "element-plus";
defineProps({
    showModifiedWarning: {
        type: Boolean,
        default: true
    },
    modifiedWarning: {
        type: String,
        default: "Warning: Parameters has changed, please reset the model."
    }
})
const paramsModel = ref<ParamsType[]>([])
const paramValues = ref<ParamValuesType>([])
const paramsModified = ref(false)
const onUpdate = (index: number, evt: ParamValue) => {

    paramValues.value[index] = evt
    updated()
}

const onUpdateSingleItem = (index: number, evt: FormValueTypes) => {
    paramValues.value[index].value = evt
    updated()
}

const updated = () => {
    paramsModified.value = true
}

const setupModels = (models: ParamsType[]) => {
    paramsModel.value = models
}

const setupValues = (values: ParamValuesType) => {
    paramValues.value = values
}

const getValues = () => {
    return paramValues.value
}

const setUnmodified = () => {
    paramsModified.value = false
}
defineExpose({ setupModels, setupValues, getValues, setUnmodified });
</script>

<style scoped>
.form-container {
    width: var(--form-width);
}
</style>